package com.xaaef.k8sdemo.consumer;

import cn.hutool.core.util.StrUtil;
import feign.FeignException;
import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class FeignProviderFallback implements FallbackFactory<FeignProviderService> {

    @Override
    public FeignProviderService create(Throwable cause) {
        var httpStatusCode = 500;
        if (cause instanceof FeignException err) {
            if (err.status() > 0) {
                httpStatusCode = err.status();
            }
            if (err instanceof RetryableException err1) {
                log.error(err1.getMessage());
            }
            if (err instanceof FeignException.FeignServerException err2) {
                log.error(err2.getMessage());
            }
            if (err instanceof FeignException.FeignClientException err3) {
                log.error(err3.getMessage());
            }
        } else {
            if (cause instanceof RuntimeException err) {
                httpStatusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
                log.error(err.getMessage());
            }
        }
        var msg = StrUtil.format("[ RpcProviderService ] k8s-provider 服务不可用: {}", cause.getMessage());
        log.error(msg);
        return new FeignProviderService() {
            @Override
            public String hello(String name) {
                return msg;
            }
        };
    }

}
